package edu.stanford.bmir.protege.web.server.scene;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.thoughtworks.xstream.XStream;

import edu.stanford.bmir.protege.web.client.rpc.data.layout.PortletConfiguration;
import edu.stanford.bmir.protege.web.client.rpc.data.layout.ProjectLayoutConfiguration;
import edu.stanford.bmir.protege.web.client.rpc.data.layout.TabColumnConfiguration;
import edu.stanford.bmir.protege.web.client.rpc.data.layout.TabConfiguration;
import edu.stanford.bmir.protege.web.client.ui.ontology.scene.service.SceneService;
import edu.stanford.bmir.protege.web.server.UIConfigurationManagerException;
import edu.stanford.bmir.protege.web.server.filesubmission.FileUploadConstants;

public class SceneServiceImpl extends RemoteServiceServlet implements SceneService {

	private final File uploadsDirectory = FileUploadConstants.UPLOADS_DIRECTORY;
	
	public ProjectLayoutConfiguration getProjectLayoutConfiguration( ) {
		try {
            InputStream inputStream = new FileInputStream ( getUIConfigurationFile() );
            ProjectLayoutConfiguration configuration = convertXMLToConfiguration(inputStream);
            inputStream.close();
            return configuration;
        }
        catch (IOException e) {
            throw new UIConfigurationManagerException(e.getMessage());
        }
	}
	
	  private File getUIConfigurationFile() {
	    	
	    	String path = uploadsDirectory.getAbsolutePath()+"/config.xml";
	    	path = path.replace("uploads", "default-ui-configuration-data");
	    	System.out.println( path );
	    	File file = new File (path);
	    	
	    	return file;
	    }
	    
	    public ProjectLayoutConfiguration convertXMLToConfiguration(InputStream in) {
	        XStream xstream = new XStream();
	        xstream.alias("project", ProjectLayoutConfiguration.class);
	        xstream.alias("tab", TabConfiguration.class);
	        xstream.alias("portlet", PortletConfiguration.class);
	        xstream.alias("column", TabColumnConfiguration.class);
	        xstream.alias("map", LinkedHashMap.class);
	        ProjectLayoutConfiguration configuration = (ProjectLayoutConfiguration) xstream.fromXML(in);
	        return configuration;
	    }

}
